package org.lee.validation.service;

import org.lee.validation.vo.User;
import org.lee.validation.vo.resp.Result;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * ValidatService
 *
 * @author dralee
 * @date 2021-12-28 11:11:20
 **/
public class ValidateService {

    public Result valid(User user) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Set<ConstraintViolation<User>> valErrs = factory.getValidator().validate(user);
        if (valErrs.isEmpty()) {
            return Result.success();
        }
        StringBuilder sb = new StringBuilder(valErrs.size() * 64);
        for (ConstraintViolation<User> err : valErrs) {
            sb.append(err.getPropertyPath()).append(",").append(err.getMessage()).append(";");
        }
        return Result.fail(401, sb.toString());
    }
}
